package cn.kgc.springboot.interceptor;

import cn.kgc.springboot.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 非法请求拦截器
 * @author mosin
 * date 2021/12/16
 * @version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //注入redis工具类
    @Autowired
    private  RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求被拦截!");
        //从请求头中获取身份认证信息
        String token = request.getHeader("token");
        if(token==null){
            response.sendRedirect(request.getContextPath()+"/user/tologin");
            return  false;
        }

        //根据用户传递的token 到redis中查找 是否存在
        String user = redisUtil.getStr(token);
        if(user==null){
            response.sendRedirect(request.getContextPath()+"/user/tologin");
            return  false;
        }

        // Object user = request.getSession().getAttribute("user");
       //  if(user==null){
       //      response.sendRedirect(request.getContextPath()+"/user/tologin");
       //      return  false;
       //  }

        return true;
    }
}
